package com.lanhai.agv.push;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

/**
 * 消息发送处理（线程组）
 * 
 * @author virus408
 *
 */
public class MsgPushThread {
	boolean running;
	Thread[] th;

	public void Start(int num) {
		th = new Thread[num];
		running = true;
		for (int i = 0; i < num; i++) {
			th[i] = new Thread() {

				@Override
				public void run() {
					while (running) {
						try {
							MsgData item = MsgQueue.Pop();
							if (item == null) {
								Thread.sleep(100);
							} else {
								try {

									ByteArrayOutputStream baos = new ByteArrayOutputStream();
									DataOutputStream dos = new DataOutputStream(baos);
									DatagramSocket ds = new DatagramSocket(0);// 让java随机指定端口

									dos.write(item.getData());
									byte[] buf = baos.toByteArray();
									DatagramPacket dp = new DatagramPacket(buf, buf.length,
											new InetSocketAddress(item.getIp(), item.getPort()));

									ds.send(dp);
									ds.close();
								} catch (Exception e1) {

								}
							}

						} catch (Exception e) {

						}
					}
				}

			};
			th[i].start();
		}
	}

	public void Stop() {
		running = false;
		for (int i = 0; i < th.length; i++) {
			try {
				th[i].interrupt();
				th[i] = null;
			} catch (Exception e) {

			}
		}
	}

}
